package me.jollyfly.jshop.user.server

import me.jollyfly.jshop.user.client.model.UserDO
import java.nio.charset.Charset
import java.security.MessageDigest
import java.util.*

/**
 *  @author wanzhichao
 *
 */
object StringUserTokenFactory {

    private val digest = MessageDigest.getInstance("MD5")


    fun createToken(userDO: UserDO): String {
        val uid: String = StringBuilder(UUID.randomUUID().toString())
                .append(userDO.username)
                .append(":")
                .append(System.currentTimeMillis()).toString()
        digest.update(uid.toByteArray(Charset.forName("utf-8")))
        val md5Array = digest.digest()
        val strBuilder = StringBuilder()
        (0 until md5Array.size)
                .map { 0xff and md5Array[it].toInt() }
                .map { Integer.toHexString(it) }
                .forEach {
                    if (it.length == 1) {
                        strBuilder.append("0").append(it)
                    } else {
                        strBuilder.append(it)
                    }
                }
        return strBuilder.toString()
    }

}

fun main(args: Array<String>) {
    val userDo = UserDO();
    userDo.username = "admin"
    println(StringUserTokenFactory.createToken(userDo))
}